iT邦幫忙

0

[Python OpenCV] 批量圖片轉影片、影片處理

  • 分享至 

  • xImage
  •  

在製作影像和逐幀處理一些視覺化的專案,時常會使用到OpenCV做影片的讀寫。以下提供圖片轉影像、影像轉影像的兩個寫法。

導入套件與影像方法

from pathlib import Path
import tqdm
import cv2

def set_camera(filename: str, width: int, height: int, 
               fps: float = 30.0, fourcc: str = 'mp4v') -> cv2.VideoWriter:
    return cv2.VideoWriter(
        filename,
        fourcc=cv2.VideoWriter_fourcc(*fourcc),
        fps=fps,
        frameSize=(width, height)
    )

(1)批量影像轉影片

batch_images = sorted(Path('path/to/batch/dir').glob('*.jpg'))
video_output_path = 'video.mp4'

camera = None
for ip in tqdm.tqdm(batch_images):
    frame = cv2.imread(ip.as_posix())
    
    # process ...
    
    if camera is None:
        h, w, _ = frame.shape
        camera = set_camera(video_output_path, w, h)
    camera.write(frame)
camera.release()

(2)影片轉影片

video = cv2.VideoCapture('path/to/video.mp4')
video_output_path = 'video.mp4'

camera = None
for i in tqdm.trange(int(video.get(7))):
    _, frame = video.read()
    
    # process ...
    
    if camera is None:
        h, w, _ = frame.shape
        camera = set_camera(video_output_path, w, h)
    camera.write(frame)
camera.release()

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言